<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-if="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="支付平台ID" prop="typeId">
              <el-input v-model="queryParams.typeId" placeholder="请输入支付平台ID" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="平台名称" prop="name">
              <el-input v-model="queryParams.name" placeholder="请输入平台名称" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="平台标识" prop="code">
              <el-input v-model="queryParams.code" placeholder="请输入平台标识" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="状态" prop="status">
              <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
                <el-option v-for="dict in pay_type_status" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-tooltip :content="showSearch ? '隐藏搜索' : '显示搜索'" placement="top">
      <div ref="searchIcon" class="search_icon" :class="showSearch ? 'show' : 'hide'" @click="showSearch = !showSearch">
        <svg-icon icon-class="commencement"></svg-icon>
      </div>
    </el-tooltip>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button v-hasPermi="['system:PayType:add']" type="primary" plain icon="Plus" @click="handleAdd">新增</el-button>
          </el-col>
          <!-- <el-col :span="1.5">
            <el-button v-hasPermi="['system:PayType:edit']" type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()"
              >修改</el-button
            >
          </el-col> -->
          <el-col :span="1.5">
            <el-button v-hasPermi="['system:PayType:remove']" type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()"
              >删除</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button v-hasPermi="['system:PayType:export']" type="warning" plain icon="Download" @click="handleExport">导出</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @query-table="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" :data="PayTypeList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column v-if="true" label="支付平台ID" align="center" prop="typeId" />
        <el-table-column label="平台名称" align="center" prop="name" />
        <el-table-column label="平台标识" align="center" prop="code" />
        <el-table-column label="公共可见" align="center" prop="config">
          <template #default="{ row }">
            <div>
              <el-switch
                v-if="row.code != 'stripe' && row.code != 'paypal' && row.code != 'square'"
                v-model="row.common"
                :active-value="1"
                :inactive-value="0"
                @change="changeCommon(row)"
              ></el-switch>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="平台配置" align="center" prop="config" show-overflow-tooltip />
        <el-table-column label="状态" align="center" prop="status">
          <template #default="scope">
            <dict-tag :options="pay_type_status" :value="scope.row.status" />
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="修改" placement="top">
              <el-button v-hasPermi="['system:PayType:edit']" link type="primary" icon="Edit" @click="handleUpdate(scope.row)">修改</el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button v-hasPermi="['system:PayType:remove']" link type="danger" icon="Delete" @click="handleDelete(scope.row)">删除</el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total > 0"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        :page-sizes="[20, 50, 100, 300]"
        :total="total"
        @pagination="getList"
      />
    </el-card>
    <!-- 添加或修改支付平台对话框 -->
    <el-dialog v-model="dialog.visible" :title="dialog.title" width="900px" append-to-body>
      <el-form ref="PayTypeFormRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="平台名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入平台名称" />
        </el-form-item>
        <el-form-item label="平台标识" prop="code">
          <el-input v-model="form.code" placeholder="请输入平台标识" />
        </el-form-item>
        <el-form-item label="公共可见" prop="code">
          <el-switch v-model="form.common" :active-value="1" :inactive-value="0"></el-switch>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio v-for="dict in pay_type_status" :key="dict.value" :value="parseInt(dict.value)">{{ dict.label }}</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="平台配置" prop="config">
          <CodeMirror v-model="form.config" />
        </el-form-item>

        <el-form-item label="配置示例" v-hasPermi="['system:config:configExample']">
          <el-tooltip class="box-item" effect="dark" content="点击查看示例" placement="top">
            <el-icon style="font-size: 24px" @click="viewExample"><QuestionFilled /></el-icon>
          </el-tooltip>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="PayType" lang="ts">
import CodeMirror from '@/components/CodeMirror/index.vue';
import { listPayType, getPayType, delPayType, addPayType, updatePayType } from '@/api/pay/PayType';
import { PayTypeVO, PayTypeQuery, PayTypeForm } from '@/api/pay/PayType/types';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { pay_type_status } = toRefs<any>(proxy?.useDict('pay_type_status'));

const PayTypeList = ref<PayTypeVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(false);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const queryFormRef = ref<ElFormInstance>();
const PayTypeFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: PayTypeForm = {
  name: undefined,
  code: undefined,
  config: '',
  status: 1
};
const data = reactive<PageData<PayTypeForm, PayTypeQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 20,
    typeId: undefined,
    name: undefined,
    code: undefined,
    status: undefined,
    params: {}
  },
  rules: {
    name: [{ required: true, message: '平台名称不能为空', trigger: 'blur' }],
    code: [{ required: true, message: '平台标识不能为空', trigger: 'blur' }],
    config: [{ required: true, message: '平台配置不能为空', trigger: 'blur' }],
    status: [{ required: true, message: '状态不能为空', trigger: 'change' }]
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询支付平台列表 */
const getList = async () => {
  loading.value = true;
  const res = await listPayType(queryParams.value);
  PayTypeList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
};

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  PayTypeFormRef.value?.resetFields();
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};

/** 多选框选中数据 */
const handleSelectionChange = (selection: PayTypeVO[]) => {
  ids.value = selection;
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = '添加支付平台';
};

/** 修改按钮操作 */
const handleUpdate = async (row?: PayTypeVO) => {
  reset();
  const _typeId = row?.typeId || ids.value[0];
  const res = await getPayType(_typeId);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = '修改支付平台';
};

/** 提交按钮 */
const submitForm = () => {
  PayTypeFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      if (form.value.config) {
        if (!isJSON(form.value?.config.replace(/\/\/\*\*\*.*\*\*\*.*\n/g, ''))) {
          ElMessage.error('JSON格式不对');
          return;
        }
      }
      buttonLoading.value = true;
      if (form.value.typeId) {
        await updatePayType(form.value).finally(() => (buttonLoading.value = false));
      } else {
        await addPayType(form.value).finally(() => (buttonLoading.value = false));
      }
      proxy?.$modal.msgSuccess('操作成功');
      dialog.visible = false;
      await getList();
    }
  });
};
function isJSON(str) {
  if (typeof str == 'string') {
    try {
      var obj = JSON.parse(str);
      if (typeof obj == 'object' && obj) {
        return true;
      } else {
        return false;
      }
    } catch (e) {
      return false;
    }
  }
}
/** 删除按钮操作 */
const handleDelete = async (row?: PayTypeVO) => {
  const _typeIds = row?.typeId || ids.value.map((item) => item.typeId);
  const _typeNames = row?.name || ids.value.map((item) => item.name);
  await proxy?.$modal.confirm('是否确认删除支付平台 ' + _typeNames + ' 的数据？').finally(() => (loading.value = false));
  await delPayType(_typeIds);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download(
    'system/PayType/export',
    {
      ...queryParams.value
    },
    `PayType_${new Date().getTime()}.xlsx`
  );
};

/**
 * 更改公共可见
 */
const changeCommon = (row) => {
  ElMessageBox.confirm(`当前操作时设置为公共${row.common ? '可见' : '不可见'}，确定操作吗？`, 'Warning', {
    confirmButtonText: 'OK',
    cancelButtonText: 'Cancel',
    type: 'warning'
  })
    .then(() => {
      updatePayType({
        ...row,
        common: row.common ? 1 : 0
      });
    })
    .catch(() => {
      row.common = row.common ? 0 : 1;
    });
};
const router = useRouter();
const viewExample = () => {
  window.open('/configExample');
};

onMounted(() => {
  getList();
});
</script>

<style lang="scss" scoped>
.cm-component {
  font-family: monospace;
}
:deep(.el-form-item__label) {
  width: fit-content;
}
</style>
